<template>
  <view :style="style">
    <image :src="img + debug" v-if="status === 0" mode="aspectFit"
           @error="onImageError"
           @load="onImageLoaded"
           style="height: 0"></image>
    <view v-if="status === 0" class="tips" @click="reloadImage">加载中..</view>
    <view class="pic" v-else-if="status === 1" :style="{'background-image': styleBgImageUrl(img)}"
          @click="onClick"></view>
    <view v-else-if="status === -1" class="tips" @click="reloadImage">图片加载失败，点击重试</view>
    <view class="z-img-id">{{ imgId }}</view>
  </view>
</template>

<script>
import {styleBgImageUrl} from "../libs/utils";

export default {
  name: "ZImage",
  props: ['img', 'style'],
  data() {
    return {
      status: 0,
      debug: ''
    }
  },
  watch: {
    img(val) {
      console.log('watch, img')
      this.status = 0
      this.debug = ''
      console.log(val, '开始')
    },
  },
  computed: {
    imgId() {
      if (this.img) {
        const arr = this.img.split('/')
        return arr[arr.length - 1]
      }

      return ''
    }
  },
  methods: {
    styleBgImageUrl,
    reloadImage() {
      this.status = 0
      this.debug = ''
    },
    onImageError() {
      this.status = -1
      console.log(this.img, 'failed')
    },
    onImageLoaded(e) {
      this.status = 1
      console.log(this.img, 'success', e)
    },
    onClick() {
      this.$emit('click')
    }
  }
}
</script>


<style lang="scss">
.tips {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 16px;
  background-color: #f9f9f9;
}

.z-img-id {
  position: absolute;
  right: 0;
  bottom: 0;
  color: #ddd;
  font-size: 12px;
}

.pic {
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  width: 100%;
  height: 100%;
}
</style>
